<template>
  <div class="drawing-page">
    <div class="drawing-header">
      <div class="tool-selector">
        <el-radio-group v-model="selectedTool" @change="onToolChange">
          <el-radio-button label="rect">矩形</el-radio-button>
          <el-radio-button label="circle">圆形</el-radio-button>
          <el-radio-button label="line">线条</el-radio-button>
          <el-radio-button label="select">选择</el-radio-button>
          <!-- <el-radio-button label="delete">删除</el-radio-button> -->
        </el-radio-group>
        
        <el-color-picker v-model="strokeColor" class="color-picker" size="small"></el-color-picker>
        
        <!-- <el-slider v-model="strokeWidth" :min="1" :max="10" show-input size="small" class="stroke-width"></el-slider> -->
        
        <el-button @click="clearCanvas" type="danger" size="small">清空画布</el-button>
        <el-button @click="saveCanvas" type="primary" size="small">保存图片</el-button>
      </div>
    </div>
    
    <div class="drawing-canvas-container">
      <canvas 
        ref="canvas"
        :width="canvasWidth"
        :height="canvasHeight"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
        class="drawing-canvas"
      ></canvas>
       <div class="drawing-info" v-if="selectedShape">
      <el-descriptions border :column="{xs:1, sm:2, md:4, lg:4, xl:4, xxl:4}">
        <!-- <el-descriptions-item label="类型">{{ getShapeType(selectedShape.type) }}</el-descriptions-item> -->
        <!-- <el-descriptions-item label="颜色">{{ selectedShape.color }}</el-descriptions-item> -->
        <!-- <el-descriptions-item label="线宽">{{ selectedShape.width }}</el-descriptions-item> -->
        <el-descriptions-item label="操作">
          <!-- <el-button @click="editShape" size="small" type="primary">编辑</el-button> -->
          <el-button @click="deleteSelectedShape" size="small" type="danger">删除</el-button>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    </div>
    
    <!-- <div class="drawing-info" v-if="selectedShape">
      <el-descriptions border :column="{xs:1, sm:2, md:4, lg:4, xl:4, xxl:4}">
        <el-descriptions-item label="类型">{{ getShapeType(selectedShape.type) }}</el-descriptions-item>
        <el-descriptions-item label="颜色">{{ selectedShape.color }}</el-descriptions-item>
        <el-descriptions-item label="线宽">{{ selectedShape.width }}</el-descriptions-item>
        <el-descriptions-item label="操作">
          <el-button @click="editShape" size="small" type="primary">编辑</el-button>
          <el-button @click="deleteSelectedShape" size="small" type="danger">删除</el-button>
        </el-descriptions-item>
      </el-descriptions>
    </div> -->
  </div>
</template>

<script>
export default {
  name: 'DrawingTool',
  data() {
    return {
      selectedTool: 'rect', // 默认选择矩形
      strokeColor: '#1890ff', // 默认颜色
      strokeWidth: 3, // 默认线宽
      canvasWidth: 800, // 画布宽度
      canvasHeight: 600, // 画布高度
      isDrawing: false, // 是否正在绘图
      startX: 0, // 起始X坐标
      startY: 0, // 起始Y坐标
      currentShape: null, // 当前正在绘制的图形
      shapes: [], // 已绘制的所有图形
      selectedShape: null, // 当前选中的图形
      editingShape: false // 是否正在编辑图形
    }
  },
  mounted() {
    // 初始化画布
    this.initCanvas()
  },
  methods: {
    // 初始化画布
    initCanvas() {
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      // 设置画布背景
      ctx.fillStyle = '#f5f5f5'
      ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight)
      
      // 添加默认图案：一个圆圈和中央十字
      this.addDefaultPattern()
    },
    
    // 添加默认图案
    addDefaultPattern() {
      const canvas = this.$refs.canvas
      const radius = 200
      const centerX = canvas.width / 2 -radius/2
      const centerY = canvas.height / 2
      
      // 添加圆圈
      const circleShape = {
        type: 'circle',
        x1: centerX,
        y1: centerY,
        x2: centerX + radius,
        y2: centerY,
        color: '#000000',
        width: 2,
        id: Date.now(), // 唯一标识符
        isDefault: true // 默认图案标记
      }
      this.shapes.push(circleShape)
      
      // 添加水平十字线
      const horizontalLineShape = {
        type: 'line',
        x1: centerX+10,
        y1: centerY,
        x2: centerX + radius-10,
        y2: centerY,
        color: '#000000',
        width: 2,
        id: Date.now() + 1, // 唯一标识符
        isDefault: true // 默认图案标记
      }
      this.shapes.push(horizontalLineShape)
      
      // 添加垂直十字线
      const verticalLineShape = {
        type: 'line',
        x1: centerX+radius/2,
        y1: centerY - radius/2+10,
        x2: centerX+radius/2,
        y2: centerY + radius/2-10,
        color: '#000000',
        width: 2,
        id: Date.now() + 2, // 唯一标识符
        isDefault: true // 默认图案标记
      }
      this.shapes.push(verticalLineShape)
      
      // 重绘画布以显示默认图案
      this.redrawCanvas()
    },
    
    // 工具选择变化
    onToolChange() {
      this.selectedShape = null
      this.editingShape = false
    },
    
    // 开始绘图
    startDrawing(e) {
      const canvas = this.$refs.canvas
      const rect = canvas.getBoundingClientRect()
      this.startX = e.clientX - rect.left
      this.startY = e.clientY - rect.top
      this.isDrawing = true
      
      if (this.selectedTool === 'select') {
        this.selectShape(this.startX, this.startY)
      } else if (this.selectedTool === 'delete' && this.selectedShape) {
        this.deleteSelectedShape()
      } else if (['rect', 'circle', 'line'].includes(this.selectedTool)) {
        // 创建新图形
        this.currentShape = {
          type: this.selectedTool,
          x1: this.startX,
          y1: this.startY,
          x2: this.startX,
          y2: this.startY,
          color: this.strokeColor,
          width: this.strokeWidth,
          id: Date.now() // 唯一标识符
        }
      }
    },
    
    // 绘制过程
    draw(e) {
      if (!this.isDrawing || this.selectedTool === 'select' || this.selectedTool === 'delete') {
        return
      }
      
      const canvas = this.$refs.canvas
      const rect = canvas.getBoundingClientRect()
      const currentX = e.clientX - rect.left
      const currentY = e.clientY - rect.top
      
      // 更新当前图形的结束坐标
      if (this.currentShape) {
        this.currentShape.x2 = currentX
        this.currentShape.y2 = currentY
      }
      
      // 重绘画布
      this.redrawCanvas()
      
      // 绘制当前正在创建的图形
      if (this.currentShape) {
        this.drawShape(this.$refs.canvas.getContext('2d'), this.currentShape)
      }
    },
    
    // 停止绘图
    stopDrawing() {
      if (!this.isDrawing || this.selectedTool === 'select' || this.selectedTool === 'delete') {
        this.isDrawing = false
        return
      }
      
      this.isDrawing = false
      
      // 将当前图形添加到已绘制图形列表
      if (this.currentShape) {
        // 确保图形有一定的大小，避免添加过小的图形
        const minSize = 5
        const width = Math.abs(this.currentShape.x2 - this.currentShape.x1)
        const height = Math.abs(this.currentShape.y2 - this.currentShape.y1)
        
        if ((this.currentShape.type === 'rect' && (width >= minSize || height >= minSize)) ||
            (this.currentShape.type === 'circle' && width >= minSize) ||
            (this.currentShape.type === 'line' && (width >= minSize || height >= minSize))) {
          this.shapes.push(this.currentShape)
        }
        
        this.currentShape = null
        this.redrawCanvas()
      }
    },
    
    // 重绘画布
    redrawCanvas() {
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      
      // 清空画布
      ctx.fillStyle = '#f5f5f5'
      ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight)
      
      // 绘制所有已保存的图形
      this.shapes.forEach(shape => {
        this.drawShape(ctx, shape)
      })
    },
    
    // 绘制单个图形
    drawShape(ctx, shape) {
      ctx.strokeStyle = shape.color
      ctx.lineWidth = shape.width
      ctx.lineCap = 'round'
      ctx.lineJoin = 'round'
      ctx.beginPath()
      
      switch (shape.type) {
        case 'rect':
          const rectX = Math.min(shape.x1, shape.x2)
          const rectY = Math.min(shape.y1, shape.y2)
          const rectWidth = Math.abs(shape.x2 - shape.x1)
          const rectHeight = Math.abs(shape.y2 - shape.y1)
          ctx.strokeRect(rectX, rectY, rectWidth, rectHeight)
          break
        case 'circle':
          const centerX = (shape.x1 + shape.x2) / 2
          const centerY = (shape.y1 + shape.y2) / 2
          const radius = Math.sqrt(Math.pow(shape.x2 - shape.x1, 2) + Math.pow(shape.y2 - shape.y1, 2)) / 2
          ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI)
          ctx.stroke()
          break
        case 'line':
          ctx.moveTo(shape.x1, shape.y1)
          ctx.lineTo(shape.x2, shape.y2)
          ctx.stroke()
          break
      }
      
      // 如果是选中的图形，绘制选中状态
      if (this.selectedShape && this.selectedShape.id === shape.id) {
        ctx.strokeStyle = '#ff4d4f'
        ctx.setLineDash([5, 5])
        
        switch (shape.type) {
          case 'rect':
            const rectX = Math.min(shape.x1, shape.x2)
            const rectY = Math.min(shape.y1, shape.y2)
            const rectWidth = Math.abs(shape.x2 - shape.x1)
            const rectHeight = Math.abs(shape.y2 - shape.y1)
            ctx.strokeRect(rectX - 2, rectY - 2, rectWidth + 4, rectHeight + 4)
            break
          case 'circle':
            const centerX = (shape.x1 + shape.x2) / 2
            const centerY = (shape.y1 + shape.y2) / 2
            const radius = Math.sqrt(Math.pow(shape.x2 - shape.x1, 2) + Math.pow(shape.y2 - shape.y1, 2)) / 2
            ctx.arc(centerX, centerY, radius + 2, 0, 2 * Math.PI)
            ctx.stroke()
            break
          case 'line':
            // 对于线条，绘制一个包围矩形
            const minX = Math.min(shape.x1, shape.x2)
            const minY = Math.min(shape.y1, shape.y2)
            const maxX = Math.max(shape.x1, shape.x2)
            const maxY = Math.max(shape.y1, shape.y2)
            ctx.strokeRect(minX - 2, minY - 2, maxX - minX + 4, maxY - minY + 4)
            break
        }
        
        ctx.setLineDash([])
      }
    },
    
    // 选择图形 - 跳过默认图案
    selectShape(x, y) {
      // 从后往前遍历，优先选择后绘制的图形
      for (let i = this.shapes.length - 1; i >= 0; i--) {
        const shape = this.shapes[i]
        // 跳过默认图案，它们不能被选择
        if (!shape.isDefault && this.isPointInShape(x, y, shape)) {
          this.selectedShape = shape
          this.redrawCanvas()
          return
        }
      }
      // 如果没有选中任何图形，清空选择
      this.selectedShape = null
      this.redrawCanvas()
    },
    
    // 判断点是否在图形内
    isPointInShape(x, y, shape) {
      // 简单的碰撞检测，实际应用中可能需要更精确的算法
      const tolerance = 10 // 容差，方便用户选择
      
      switch (shape.type) {
        case 'rect':
          const rectX = Math.min(shape.x1, shape.x2)
          const rectY = Math.min(shape.y1, shape.y2)
          const rectWidth = Math.abs(shape.x2 - shape.x1)
          const rectHeight = Math.abs(shape.y2 - shape.y1)
          return x >= rectX - tolerance && x <= rectX + rectWidth + tolerance &&
                 y >= rectY - tolerance && y <= rectY + rectHeight + tolerance
        case 'circle':
          const centerX = (shape.x1 + shape.x2) / 2
          const centerY = (shape.y1 + shape.y2) / 2
          const radius = Math.sqrt(Math.pow(shape.x2 - shape.x1, 2) + Math.pow(shape.y2 - shape.y1, 2)) / 2
          const distance = Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2))
          return distance <= radius + tolerance
        case 'line':
          // 计算点到线段的距离
          const A = x - shape.x1
          const B = y - shape.y1
          const C = shape.x2 - shape.x1
          const D = shape.y2 - shape.y1
          
          const dot = A * C + B * D
          const lenSq = C * C + D * D
          let param = -1
          if (lenSq !== 0) param = dot / lenSq
          
          let xx, yy
          
          if (param < 0) {
            xx = shape.x1
            yy = shape.y1
          } else if (param > 1) {
            xx = shape.x2
            yy = shape.y2
          } else {
            xx = shape.x1 + param * C
            yy = shape.y1 + param * D
          }
          
          const dx = x - xx
          const dy = y - yy
          return Math.sqrt(dx * dx + dy * dy) <= tolerance
      }
      
      return false
    },
    
    // 清空画布 - 保留默认图案
    clearCanvas() {
      // 只保留默认图案
      this.shapes = this.shapes.filter(shape => shape.isDefault === true)
      this.selectedShape = null
      this.redrawCanvas()
    },
    
    // 删除选中的图形
    deleteSelectedShape() {
      if (this.selectedShape) {
        const index = this.shapes.findIndex(shape => shape.id === this.selectedShape.id)
        if (index !== -1) {
          this.shapes.splice(index, 1)
        }
        this.selectedShape = null
        this.redrawCanvas()
      }
    },
    
    // 编辑图形
    editShape() {
      // 这里可以实现图形编辑功能
      // 简单示例：更改选中图形的颜色和线宽
      if (this.selectedShape) {
        this.selectedShape.color = this.strokeColor
        this.selectedShape.width = this.strokeWidth
        this.redrawCanvas()
        this.$message.success('图形已更新')
      }
    },
    
    // 获取图形类型的中文名称
    getShapeType(type) {
      const typeMap = {
        rect: '矩形',
        circle: '圆形',
        line: '线条'
      }
      return typeMap[type] || type
    },
    
    // 保存Canvas为图片并上传
    saveCanvas() {
      // 导入request模块
      import('@/utils/request').then(({ default: request }) => {
        const canvas = this.$refs.canvas
        
        // 检查画布是否为空（除了背景色）
        if (this.shapes.length === 0) {
          this.$message.warning('画布为空，无需保存')
          return
        }
        
        // 将Canvas内容转换为blob对象
        canvas.toBlob((blob) => {
          // 创建FormData对象
          const formData = new FormData()
          // 添加文件到FormData
          formData.append('file', blob, `drawing_${Date.now()}.png`)
          
          // 显示上传中提示
          const loading = this.$loading({
            lock: true,
            text: '图片上传中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          
          // 发送POST请求上传图片
          request({
            url: '/admin/resource/upload', // 使用项目中已有的上传接口
            method: 'post',
            data: formData,
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(res => {
            loading.close()
            
            if (res.code === 200) {
              this.$message.success('图片保存成功')
              console.log('上传成功，返回数据:', res)
              // 这里可以处理上传成功后的逻辑，例如获取图片URL等
            } else {
              this.$message.error(`图片保存失败: ${res.msg || '未知错误'}`)
            }
          }).catch(error => {
            loading.close()
            this.$message.error('图片上传失败，请检查网络连接')
            console.error('上传失败:', error)
          })
        })
      }).catch(error => {
        console.error('导入request模块失败:', error)
        this.$message.error('导入请求模块失败')
      })
    }
  }
}
</script>

<style scoped>
.drawing-page {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.drawing-header {
  margin-bottom: 20px;
}

.drawing-header h3 {
  margin: 0 0 15px 0;
  color: #303133;
}

.tool-selector {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.color-picker {
  width: 100px;
}

.stroke-width {
  width: 150px;
}

.drawing-canvas-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 20px;
  display: flex;
}

.drawing-canvas {
  background-color: #f5f5f5;
  cursor: crosshair;
}

.drawing-canvas:hover {
  cursor: crosshair;
}

.drawing-info {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

/* 选择工具时的光标样式 */
.drawing-canvas.select-tool {
  cursor: pointer;
}

/* 删除工具时的光标样式 */
.drawing-canvas.delete-tool {
  cursor: not-allowed;
}
</style>